package com.czxy.service;

import com.alibaba.fastjson.JSON;
import com.czxy.mapper.SkuCommentMapper;
import com.czxy.mapper.SkuMapper;
import com.czxy.mapper.SpuMapper;
import com.czxy.pojo.Sku;
import com.czxy.pojo.Spu;
import com.czxy.vo.ESData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 张青卯
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EsDataService {

    private final SkuMapper skuMapper;

    private final SpuMapper spuMapper;

    private final SkuCommentMapper skuCommentMapper;

    @Autowired
    public EsDataService(SkuMapper skuMapper,SpuMapper spuMapper,SkuCommentMapper skuCommentMapper) {
        this.skuMapper = skuMapper;
        this.spuMapper = spuMapper;
        this.skuCommentMapper = skuCommentMapper;
    }

    public List<ESData> findAll(){
        ArrayList<ESData> esDataList = new ArrayList<>();
        List<Sku> list = skuMapper.selectAll();
        for (Sku sku : list) {
            ESData data = new ESData();
            data.setId(sku.getId());
            data.setLogo(sku.getImages());
            data.setSku_name(sku.getSku_name());
            Spu spu = spuMapper.findSpuBySpuId(sku.getSpu_id());
            String all = sku.getSku_name()+" "+spu.getBrand().getBrandName()+" "+spu.getCat3().getCatName();
            data.setAll(all);
            Date onSaleTime = spu.getOn_sale_time();
            long time = onSaleTime.getTime();
            data.setOn_sale_time(time);
            data.setBrand_id(spu.getBrand().getId());
            data.setCat3_id(spu.getCat3().getId());
            Map specs = JSON.parseObject(sku.getSpec_list_code(), Map.class);
            data.setSpecs(specs);
            data.setPrice(sku.getPrice());
            data.setSpu_name(spu.getSpu_name());
            data.setStock(sku.getStock());
            data.setDescription(spu.getDescription());
            data.setPackages(spu.getPackages());
            data.setAftersale(spu.getAftersale());
            Integer count = skuCommentMapper.findCountBySpuId(spu.getId());
            data.setComment_count(count);
            Integer count1 = skuMapper.findSellCountBySkuId(sku.getId());
            data.setSeller_count(count1);
            esDataList.add(data);
        }
        return esDataList;
    }
}
